package controllers

import (
	"strconv"
	"time"

	"simple-crm/models"
	"simple-crm/services"
	"simple-crm/utils"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type SystemController struct {
	db                *gorm.DB
	permissionService *services.PermissionService
}

func NewSystemController(db *gorm.DB, permissionService *services.PermissionService) *SystemController {
	return &SystemController{
		db:                db,
		permissionService: permissionService,
	}
}

// 权限管理
func (ctrl *SystemController) GetPermissions(c *gin.Context) {
	var permissions []models.Permission
	ctrl.db.Find(&permissions)

	utils.SuccessWithData(c, gin.H{"permissions": permissions})
}

// 操作日志
func (ctrl *SystemController) GetLogs(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
	userID := c.Query("user_id")
	action := c.Query("action")
	resource := c.Query("resource")

	offset := (page - 1) * limit

	query := ctrl.db.Model(&models.OperationLog{}).Preload("User")

	if userID != "" {
		query = query.Where("user_id = ?", userID)
	}

	if action != "" {
		query = query.Where("action LIKE ?", "%"+action+"%")
	}

	if resource != "" {
		query = query.Where("resource = ?", resource)
	}

	var total int64
	query.Count(&total)

	var logs []models.OperationLog
	query.Order("created_at DESC").Offset(offset).Limit(limit).Find(&logs)

	utils.SuccessWithData(c, gin.H{
		"logs":  logs,
		"total": total,
		"page":  page,
		"limit": limit,
	})
}

// GetOperationLogs 获取操作日志
func (ctrl *SystemController) GetOperationLogs(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
	userID := c.Query("userId")
	action := c.Query("action")
	resource := c.Query("resource")
	offset := (page - 1) * size

	var logs []models.OperationLog
	var total int64

	query := ctrl.db.Model(&models.OperationLog{})

	// 添加筛选条件
	if userID != "" {
		query = query.Where("user_id = ?", userID)
	}
	if action != "" {
		query = query.Where("action LIKE ?", "%"+action+"%")
	}
	if resource != "" {
		query = query.Where("resource = ?", resource)
	}

	query.Count(&total)
	query.Preload("User").Offset(offset).Limit(size).Order("created_at DESC").Find(&logs)

	utils.SuccessWithData(c, gin.H{
		"logs":  logs,
		"total": total,
		"page":  page,
		"size":  size,
	})
}

// GetSystemStats 获取系统统计
func (ctrl *SystemController) GetSystemStats(c *gin.Context) {
	var userCount, roleCount, permissionCount int64

	ctrl.db.Model(&models.User{}).Count(&userCount)
	ctrl.db.Model(&models.Role{}).Count(&roleCount)
	ctrl.db.Model(&models.Permission{}).Count(&permissionCount)

	stats := gin.H{
		"user_count":       userCount,
		"role_count":       roleCount,
		"permission_count": permissionCount,
	}

	utils.SuccessWithData(c, stats)
}

// SystemIndex 系统管理主页
func (ctrl *SystemController) SystemIndex(c *gin.Context) {
	// 获取统计数据
	var userCount, roleCount, operationCount int64
	ctrl.db.Model(&models.User{}).Count(&userCount)
	ctrl.db.Model(&models.Role{}).Count(&roleCount)
	ctrl.db.Model(&models.OperationLog{}).Count(&operationCount)

	stats := gin.H{
		"user_count":      userCount,
		"role_count":      roleCount,
		"operation_count": operationCount,
	}

	c.HTML(200, "system/index.html", gin.H{
		"title": "系统管理",
		"stats": stats,
	})
}

// LogsIndex 系统日志页面
func (ctrl *SystemController) LogsIndex(c *gin.Context) {
	c.HTML(200, "system/logs.html", gin.H{
		"title": "系统日志",
		"user":  c.MustGet("user"),
		"CurrentPage": "logs",
	})
}

// GetDashboardStats 获取仪表板统计
func (ctrl *SystemController) GetDashboardStats(c *gin.Context) {
	var customerCount, partnerCount, pushRecordCount, userCount int64
	var todayCustomers, todayPushes int64

	// 基础统计
	ctrl.db.Model(&models.Customer{}).Count(&customerCount)
	ctrl.db.Model(&models.Partner{}).Count(&partnerCount)
	ctrl.db.Model(&models.PushRecord{}).Count(&pushRecordCount)
	ctrl.db.Model(&models.User{}).Count(&userCount)

	// 今日统计
	today := time.Now().Format("2006-01-02")
	ctrl.db.Model(&models.Customer{}).Where("DATE(created_at) = ?", today).Count(&todayCustomers)
	ctrl.db.Model(&models.PushRecord{}).Where("DATE(created_at) = ?", today).Count(&todayPushes)

	// 客户状态统计
	var customerStats []struct {
		Status string `json:"status"`
		Count  int64  `json:"count"`
	}
	ctrl.db.Model(&models.Customer{}).Select("status, COUNT(*) as count").Group("status").Scan(&customerStats)

	// 最近7天的客户增长
	var weeklyGrowth []struct {
		Date  string `json:"date"`
		Count int64  `json:"count"`
	}
	for i := 6; i >= 0; i-- {
		date := time.Now().AddDate(0, 0, -i).Format("2006-01-02")
		var count int64
		ctrl.db.Model(&models.Customer{}).Where("DATE(created_at) = ?", date).Count(&count)
		weeklyGrowth = append(weeklyGrowth, struct {
			Date  string `json:"date"`
			Count int64  `json:"count"`
		}{Date: date, Count: count})
	}

	stats := gin.H{
		"total_customers":    customerCount,
		"total_partners":     partnerCount,
		"total_push_records": pushRecordCount,
		"total_users":        userCount,
		"today_customers":    todayCustomers,
		"today_pushes":       todayPushes,
		"customer_stats":     customerStats,
		"weekly_growth":      weeklyGrowth,
	}

	utils.SuccessWithData(c, stats)
}
